package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.CategoryMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.dto.CategoryAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Category;
import cn.tedu.csmall.product.pojo.vo.CategoryListItemVO;
import cn.tedu.csmall.product.pojo.vo.CategoryStandardVO;
import cn.tedu.csmall.product.service.ICategoryService;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandCategoryMapper brandCategoryMapper;
    @Autowired
    private SpuMapper spuMapper;

    public CategoryServiceImpl(){
        log.debug("创建业务对象：CategoryServiceImpl");
    }
    @Override
    public void addNew(CategoryAddNewDTO categoryAddNewDTO) {
        int count = categoryMapper.countByName(categoryAddNewDTO.getName());
        if (count>0){
            String message = "添加类别失败,尝试添加的类别名称已被占用!";
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryAddNewDTO,category);
        int rows = categoryMapper.insert(category);
        if (rows != 1){
            String message = "添加类别失败，服务器忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据id删除类别】的业务，参数：{}",id);
        // 检查尝试删除的数据是否存在
        Object queryResult = categoryMapper.getStandardById(id);
        if (queryResult == null){
            String message = "删除类别失败，尝试删除的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        {
            int count = brandCategoryMapper.countByCategoryId(id);
            if (count > 0) {
                String message = "删除类别失败，存在“品牌与类别的关联数据”涉及此类别！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        {
            int count = spuMapper.countByCategoryId(id);
            if (count > 0) {
                String message = "删除品牌失败，存在SPU关联到此类别！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("即将删除数据");
        int rows = categoryMapper.deleteById(id);
        if (rows != 1){
            String message = "删除类别失败，服务器忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void setEnable(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }

    @Override
    public void setIsDisplay(Long id) {
        updateIsDisplayById(id, 1);
    }

    @Override
    public void setNotDisplay(Long id) {
        updateIsDisplayById(id, 0);
    }

    @Override
    public List<CategoryListItemVO> list() {
        log.debug("开始处理【查询类别列表】的业务，参数：无");
        return categoryMapper.list();
    }

    @Override
    public List<CategoryListItemVO> listByParentId(Long parentId) {
        log.debug("开始处理【根据父级类别id查询子级类别】的业务，参数：{}", parentId);
        return categoryMapper.listByParentId(parentId);
    }

    private void updateEnableById(Long id, Integer enable){
        String[] enableText = {"禁用", "启用"};
        log.debug("开始处理【" + enableText[enable] + "类别】的业务，类别ID：{}，目标状态：{}", id, enable);
        CategoryStandardVO categoryStandardVO = categoryMapper.getStandardById(id);
        if (categoryStandardVO==null){
            String message = enableText[enable] + "类别失败，尝试访问的数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        if (categoryStandardVO.getEnable().equals(enable)){
            String message = enableText[enable] + "类别失败，当前类别已经是"
                    + enableText[enable] + "状态！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Category category = new Category();
        category.setId(id);
        category.setEnable(enable);
        log.debug("即将修改数据，参数：{}", category);
        int rows = categoryMapper.update(category);
        if (rows != 1){
            String message =enableText[enable] + "类别失败，服务器忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    private void updateIsDisplayById(Long id, Integer isDisplay){
        String[] isDisplayText = {"隐藏", "显示"};
        log.debug("开始处理【" + isDisplayText[isDisplay] + "类别】的业务，类别ID：{}，目标状态：{}", id, isDisplay);
        CategoryStandardVO categoryStandardVO = categoryMapper.getStandardById(id);
        if (categoryStandardVO==null){
            String message = isDisplayText[isDisplay] + "类别失败，尝试访问的数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        if (categoryStandardVO.getIsDisplay().equals(isDisplay)){
            String message = isDisplayText[isDisplay] + "类别失败，当前类别已经是"
                    + isDisplayText[isDisplay] + "状态！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Category category = new Category();
        category.setId(id);
        category.setIsDisplay(isDisplay);
        log.debug("即将修改数据，参数：{}", category);
        int rows = categoryMapper.update(category);
        if (rows != 1){
            String message = isDisplayText[isDisplay] + "类别失败，服务器忙，请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }
}
